package com.yun.fullstack.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yun.fullstack.common.Result;
import com.yun.fullstack.service.OSSService;
import com.yun.fullstack.util.OssUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

@Service
public class OSSServiceImpl implements OSSService {
    @Override
    public Result<?> uploadFile(MultipartFile file) {
        System.out.println(file.getContentType());
        if(file.isEmpty()||file.getSize()==0){
            return Result.error("500","文件为空");
        }
        String imageType = file.getContentType();
        String url = null;
        if (Objects.equals(imageType, "image/jpeg") || Objects.equals(imageType, "image/gif") || Objects.equals(imageType, "image/png") || Objects.equals(imageType, "image/bmp")){
            String endpoint = OssUtil.END_POINT;
            String accessKeyId = OssUtil.ACCESS_KEY_ID;
            String accessKeySecret = OssUtil.ACCESS_KEY_SECRET;
            String bucketName = OssUtil.BUCKET_NAME;
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            try {

                InputStream inputStream = file.getInputStream();
                //获取上传的文件的名字
                String filename = file.getOriginalFilename();
                //随机uuid是为了拼接文件名，防止用户上传两个名字相同的文件后覆盖掉前一个
                UUID uuid = UUID.randomUUID();
                //这里是为了按上传时间分配目录。精确到月
                String s = "messageBoard/" + LocalDateTime.now().toString().substring(0, 9)+"/";
                //拼接成完整的文件名。
                filename = s + uuid + filename;
                //传入三个参数
                ossClient.putObject(bucketName, filename, inputStream);
                //拼接url
                url = "https://" + bucketName + "." + endpoint + "/" + filename;
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("500","上传失败 未知错误");
            }finally {
                ossClient.shutdown();
            }
        }else {
            return  Result.error("500","文件类型不支持");
        }
        return Result.success(url);
    }
}

